package br.unb.core.synchronism;

import java.net.SocketException;
import java.net.UnknownHostException;

import br.unb.utils.Console;
import br.unb.utils.Resource;

import cgl.narada.sync.SyncServerDatagramPacket;
import cgl.narada.sync.SyncTimestamp;

public class ServerController extends Thread {

    int port = 0;
    boolean isRunning;
    SyncServerDatagramPacket serverDatagram; // Does the hard job

    /**
     *  Wait for samples
     */
    public ServerController(int port) throws SocketException, UnknownHostException {
        this.setName("ServerController");
        this.isRunning = false;
        this.port = port;
        serverDatagram = new SyncServerDatagramPacket(this.port);
        this.startSamples();
    }

    public void run() {
        SyncTimestamp.setInitOffset(0);
        SyncTimestamp.setRefTime(0);

        this.setPriority(Thread.MAX_PRIORITY);
        Console.println(
                Resource.getString("SERVER") + Resource.getString("WAITING_CONNECTION"));
        while (isRunning) {
            serverDatagram.receiveRequest();
            ////Resource.println("Next message must arrive in a maximum of em"+Math.pow(2,pollInterval)+"s", client);
        }
        serverDatagram.stopListening();

    }

    public void startSamples() {
        if (!isRunning) {
            isRunning = true;
            this.start();
        }
    }

    public void stopSamples() {
        isRunning = false;
        //serverDatagram.stopListening();
    }

    public int getPort() {
        return port;
    }
}
